<?php

class Service_Model_SmsMapper
{
    protected $_dbTable;
    
    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }


    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Service_Model_DbTable_Sms');
        }
        return $this->_dbTable;
    }


    public function save(Service_Model_Sms $sms)
    {
        $data = array(
            'message'   => $sms->getMessage(),
            'mobileNumber' => $sms->getMobileNumber(),
        	'originator' => $sms->getOriginator(),
            'timeCreating' => $sms->getTimeCreating(),
        	'id' => $sms->getId(),
        );
        
        if (null === ($id = $sms->getId())) {    
        	unset($data['id']);
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $id));
        }
    }

    public function find($id, Service_Model_Sms $sms)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $sms->setId($row->id)
                  ->setMessage($row->message)
                  ->setMobileNumber($row->MmobileNumber)
                  ->setTimeCreating($row->timeCreating)
                  ->setOriginator($row->originator);
    }

 

    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries   = array();
        foreach ($resultSet as $row) {
            $entry = new Service_Model_Sms();
            $entry->setId($row->id)
                  ->setMessage($row->message)
                  ->setMobileNumber($row->mobileNumber)
                  ->setTimeCreating($row->timeCreating)
                  ->setOriginator($row->originator);
            $entries[] = $entry;
        }
        return $entries;
    }

}

